package com.compiler.lexico;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;

import com.compiler.lexico.token.SymbolTable;
import com.compiler.logger.TokenPipe;


public class Analyzer {
	private Map<String, State> states;
	private Character[] characters;
	private RandomAccessFile raf;
	private SymbolTable symbolTable;
	
	public Analyzer(String fileName) {
		try {
			this.raf = new RandomAccessFile(new File(fileName), "r");
			this.states = Configuration.getInstance().getStates();
			this.characters = Configuration.getInstance().getCharacters();
			this.symbolTable = Configuration.getInstance().getSymbolTable();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private Character getCharacter(int c, String actualState) throws IOException {
		if(actualState.equals("e10") && ((char)c) == 'u') { // Caracter especial +10 para ui
			this.raf.seek(this.raf.getFilePointer()+1);
			int next = this.getChar(false);
			if(((char)next) == 'i')
				return this.characters[this.characters.length-1];
		}
		for(int x=0; x<this.characters.length; x++)
			if(this.characters[x].contains((char)c))
				return this.characters[x];
		return null;
	}
	
	private int getChar(boolean next) {
		int c = -1;
		try {
			c = this.raf.read();
			if(!next)
				this.raf.seek(raf.getFilePointer()-1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public TokenPipe start() {
		String actualState = "e0";
		int c;
		while((c = this.getChar(false)) != -1) {
			try {
				actualState = this.states.get(actualState).getNextState(getCharacter(c,actualState),this.raf).getName();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return this.symbolTable.getTokenPipe();
//		if(actualState.equals("e0")) System.out.println("Lexico: OK");
//		else System.out.println("Lexico: FAIL");
//		System.out.println(this.symbolTable);
	}

}
